package com.xnfh.network.interceptor

import com.xnfh.common.manager.UserInfoManager
import com.xnfh.framework.log.LogUtil
import com.xnfh.network.constant.REQUEST_HEADER_TOKEN
import com.xnfh.network.manager.TokenManager
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response
import java.io.IOException

/**
 * @author ziheng
 * @Description:
 * @date 2022/12/19 16:39
 */
class HeaderInterceptor : Interceptor {

    private val TAG = "HeaderInterceptor"
    @Throws(IOException::class)
    override fun intercept(chain: Chain): Response {
        val request = chain.request()
        val newBuilder = request.newBuilder()
        newBuilder.addHeader("Content-type", "application/json; charset=utf-8")

        val host = request.url().host()
        val url = request.url().toString()

        //大部分接口都需要添加token这里过滤不需要添加token的接口
        if (host.isNullOrEmpty() || !url.contains("login")) {
            val cookies = UserInfoManager.instance.getUserId()
            LogUtil.e("HeaderInterceptor:$REQUEST_HEADER_TOKEN:$cookies", tag = TAG)
            if (!cookies.isNullOrEmpty()) {
                newBuilder.addHeader(REQUEST_HEADER_TOKEN, cookies)
            }
        }
        return chain.proceed(newBuilder.build())
    }
}